//
//  DrawerViews.swift
//  Robot
//
//  Created by ming on 2025/2/19.
//

import SwiftUI

enum DragState: Equatable {
    case inactive
    case dragging(translation: CGFloat)
    
    var translation: CGFloat {
        switch self {
        case .inactive:
            return 0
        case .dragging(let t):
            return t
        }
    }
}

struct DrawerView<Content: View, Menu: View>: View {
    @Binding var isOpen: Bool
    var menuWidth: CGFloat
    var content: Content
    var menu: Menu
    
    @GestureState var dragState = DragState.inactive
    @State var offsetX: CGFloat = 0
    
    init(isOpen: Binding<Bool>,
         menuWidth: CGFloat = 300,
         @ViewBuilder content: () -> Content,
         @ViewBuilder menu: () -> Menu) {
        self._isOpen = isOpen
        self.menuWidth = menuWidth
        self.content = content()
        self.menu = menu()
    }
    
    var body: some View {
        ZStack(alignment: .leading) {
            content
                .frame(maxWidth: .infinity, maxHeight: .infinity)
                .offset(x: max(0, offsetX))
            
            if isOpen {
                Color.black
                    .opacity(0.1)
                    .ignoresSafeArea()
                    .onTapGesture { isOpen = false }
            }
            
            menu
                .frame(width: menuWidth)
                .offset(x: -menuWidth + offsetX)
                .animation(.default, value: offsetX)
        }
//        .gesture(
//            DragGesture()
//                .updating($dragState) { value, state, _ in
//                    state = .dragging(translation: value.translation.width)
//                }
//                .onEnded { value in
//                    let threshold: CGFloat = menuWidth / 2
//                    let dragDistance = value.translation.width
//                    
//                    if isOpen {
//                        if dragDistance < -threshold {
//                            isOpen = false
//                        }
//                    } else {
//                        if dragDistance > threshold {
//                            isOpen = true
//                        }
//                    }
//                }
//        )
//        .onChange(of: dragState) { oldValue, newValue in
//            if isOpen {
//                offsetX = min(menuWidth, max(0, newValue.translation))
//            } else {
//                offsetX = min(menuWidth, max(0, newValue.translation))
//            }
//        }
        .dcChange(of: isOpen) { oldValue, newValue in
            withAnimation {
                offsetX = newValue ? menuWidth : 0
            }
        }
    }
}
